package com.haiheng.voiceandbook.viewmodel

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.haiheng.voiceandbook.BookRepository.BookRepository
import com.haiheng.voiceandbook.common.BookDetailInfoDto
import com.haiheng.voiceandbook.common.BookDto
import com.haiheng.voiceandbook.download.DownLoadManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.lang.Exception

/**
 * 全局ViewModel
 */
class ApplicationViewModel constructor(application: Application) : AndroidViewModel(application) {

    val repository = BookRepository()

    /**
     * 缓存首页热门书籍，最新书籍，
     */
    fun startCancehMainBookList() {
        val TAG = "ApplicationViewModel"
        viewModelScope.launch(Dispatchers.IO) {
            try {
                Log.e(TAG, "开始执行缓存任务.....")
                val latestBookList = repository.latestRank(1, 10)
                val hotBookList = repository.hotRank(1, 10)
                val bookList = mutableListOf<BookDto>()
                bookList.addAll(latestBookList?.data)
                bookList.addAll(hotBookList?.data)
//                //分类
//                val categoriesList = repository.categories().data?.data
//                categoriesList?.forEach {
//                    val books = repository.booksByCategoryId(it.categoryId,1,20).data?.data?.books
//                    if (books != null) {
//                        bookList.addAll(books)
//                    }
//                }
                Log.e(TAG, "一共查到: ${bookList.size}本书" )
                val list = mutableListOf<BookDetailInfoDto>()
                bookList.forEach {
                    val result = repository.getBookDetail(it.getBookId()).data?.data
                    if (result != null) {
                        list.add(result)
                    }

                }
                DownLoadManager.getInstance().startDownLoadTask(list)

            } catch (e: Exception) {
                Log.e(TAG, "缓存任务异常${e.message}")
            }

        }

    }

    /**
     * 停止任务
     */
    fun stopCancehMainBookList() {
        viewModelScope.launch {
            DownLoadManager.getInstance().shutdown()
        }

    }


}